{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "b213d19f",
   "metadata": {},
   "source": [
    "# langchain中的chain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "7dab27bc",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.output_parsers import StrOutputParser"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "2180817b",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.chat_models.tongyi import ChatTongyi"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "a20a3025",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.prompts import ChatPromptTemplate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "8a9420e9",
   "metadata": {},
   "outputs": [],
   "source": [
    "prompt = ChatPromptTemplate([\n",
    "    (\"system\", \"你是一个乐于助人的AI助手\"),\n",
    "    (\"user\", \"给我讲一个关于{topic}的笑话。\")\n",
    "])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "c6a156ec",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = ChatTongyi(\n",
    "    model=\"qwen-max\",\n",
    "    api_key=\"sk-da90821cf9174fbeb854011015c67aad\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "9732e0c8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 链\n",
    "chain = prompt | model | StrOutputParser()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "e4f054d9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "当然可以，接下来是一个轻松的中秋节笑话：\n",
      "\n",
      "为什么月饼总是喜欢独自一人？\n",
      "因为它觉得自己很“饼”（棒）！ \n",
      "\n",
      "希望这个小笑话能为您的中秋佳节增添一份欢乐！\n"
     ]
    }
   ],
   "source": [
    "result = chain.invoke({\"topic\": \"中秋节\"})\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eea1817c",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "learn_langchain",
   "language": "python",
   "name": "learn_langchain"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
